package com.zjf.carpark.aspect;



import com.zjf.carpark.annotation.MyLogAnno;
import com.zjf.carpark.entities.SysLog;
import com.zjf.carpark.entities.User;
import com.zjf.carpark.service.impl.SysLogServiceImpl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

/**
 * @description:
 * @author: 张建飞
 * @createDate: 2019/12/21
 * @version: 1.0
 */
@Aspect
@Component
public class AopLoggerAspect {
    @Autowired
    private SysLogServiceImpl sysLogService;

    @Resource
    HttpServletRequest request;
    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut(value="@annotation(com.zjf.carpark.annotation.MyLogAnno)")
    public void logPointCut() {
    }
    @After("logPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        SysLog sysLog = new SysLog();
        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();
        sysLog.setLogId((UUID.randomUUID().toString()));
        //获取操作
        MyLogAnno myLog = method.getAnnotation(MyLogAnno.class);
        String value = null;
        if (myLog != null) {
            value = myLog.value();
            System.out.println(value);
        }
        //获取请求的方法名
        String methodName = method.getName();
        System.out.println("方法名"+methodName);
        User user = (User)request.getSession().getAttribute("user");
        sysLog.setLogTime(new Date());
        sysLog.setLogContent(value);
        if(user!=null)
        {
            sysLog.setUserId(user.getUserId());
            sysLogService.save(sysLog);
        }else {
            sysLog.setUserId(0);
            sysLogService.save(sysLog);
        }

    }
}
